package com.antonauoja.javaril;

import java.util.ArrayList;

public class ReadItLater {
	
	private Credentials credentials = new Credentials();
	
	public ReadItLater(Credentials cred) {
		credentials = cred;
	}
	
	public Response authenticate() {
		if (credentials.validate()) {
			AuthRequest req = new AuthRequest();
	    	return executeRequest(req);
		}
		return null;
	}
	
    public Response add(String url, String title) {
		if (credentials.validate()) {
			AddLinkRequest req = new AddLinkRequest();
			req.setLink(url, title);
	    	req.setCredentials(credentials);
	    	return executeRequest(req);
	    }
		return null;
    }
    

	public Status getInfo() {
		if (credentials.validate()) {
			InfoRequest req = new InfoRequest();
	    	req.setCredentials(credentials);
	    	
	    	String reqURL = req.getRequestURL();
	    	ConnectionHandler connection = new ConnectionHandler(reqURL);

	    	return connection.getListStatus();
		}
		return null;
    }
	
    public Response send(SendType type, ArrayList<RilItem> list) {
		if (credentials.validate()) {
	
				SendRequest req = new SendRequest();
				req.setCredentials(credentials);
				req.setRequest(type, list);
				
		    	String reqURL = req.getRequestURL();
		    	ConnectionHandler connection = new ConnectionHandler(reqURL);
		    	connection.post();
		    	return null;
		

	    }
		return null;
    }
    
    public Response register() {
    	if (credentials.validate()) {
    		RegisterRequest req = new RegisterRequest();
	    	req.setCredentials(credentials);
	    	return executeRequest(req);
    	}
    	return null;
    }


	public RilList getList(boolean isRead, boolean myAppOnly, int count) {
		if (credentials.validate()) {
				
			String read = (isRead) ? "read" : "unread";
			int myApp = (myAppOnly) ? 1 : 0;
	
			GetListRequest req = new GetListRequest();
			req.setProperties(read, myApp, count);
	    	req.setCredentials(credentials);
	    	
	    	String reqURL = req.getRequestURL();
	    	
	    	ConnectionHandler connection = new ConnectionHandler(reqURL);

			return connection.getList();
			
			}
		return null;
	}
    
    private Response executeRequest(ApiRequest req) {

    	req.setCredentials(credentials);
    	String reqURL = req.getRequestURL();
    	
    	ConnectionHandler connection = new ConnectionHandler(reqURL);

        
        //System.out.println(resp);
        
		return new Response(connection.getContent(), connection.getHeader());

    }

}
